﻿/*
 * @Author: Dreamy Icecream 
 * @Date: 2020-12-31 13:39:43 
 * @Description: 高斯模糊
 * @Last Modified by: Dreamy Icecream
 * @Last Modified time: 2020-12-31 14:33:10
 */

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GaussianBlur : PostEffectsBase {

    public Shader gaussianBlurShader;

    private Material gaussianBlurMaterial = null;
    public Material material {
        get {
            this.gaussianBlurMaterial = CheckShaderAndCreateMaterial (this.gaussianBlurShader, this.gaussianBlurMaterial);
            return this.gaussianBlurMaterial;
        }
    }

    /** 迭代次数 */
    [Range (0, 4)]
    public int iterations = 3;

    /** 范围 */
    [Range (0.2f, 3.0f)]
    public float blurSpread = 0.6f;

    /** 缩放系数 */
    public int downSample = 2;

    private void OnRenderImage (RenderTexture src, RenderTexture dest) {
        if (this.material != null) {
            int rtW = src.width / downSample;
            int rtH = src.height / downSample;
            RenderTexture buffer0 = RenderTexture.GetTemporary (rtW, rtH, 0);
            buffer0.filterMode = FilterMode.Bilinear;

            Graphics.Blit (src, buffer0);

            for (int i = 0; i < this.iterations; i++) {
                this.material.SetFloat ("_BlurSize", 1.0f + i * blurSpread);
                RenderTexture buffer1 = RenderTexture.GetTemporary (rtW, rtH, 0);

                Graphics.Blit (buffer0, buffer1, this.material, 0);

                RenderTexture.ReleaseTemporary (buffer0);
                buffer0 = buffer1;
                buffer1 = RenderTexture.GetTemporary (rtW, rtH, 0);

                Graphics.Blit (buffer0, buffer1, this.material, 1);
                RenderTexture.ReleaseTemporary (buffer0);
                buffer0 = buffer1;
            }

            Graphics.Blit (buffer0, dest);
            RenderTexture.ReleaseTemporary (buffer0);

        } else {
            Graphics.Blit (src, dest);
        }
    }

}